/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.event;

import io.iec.edp.caf.commons.event.StartupCompletedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.util.ErrorHandler;

/**
 * 扩展事件多播器，设置异常处理程序，避免一个订阅出错后造成后续事件订阅不能执行
 * 为了让当前线程不中断，那么需要设定Executor或者ErrorHandler其中之一即可。
 * 设定Executor是另起了线程处理，ErrorHandler是通过吞异常处理
 * https://www.cnblogs.com/jiangwh/p/12705104.html
 * @author wangyandong
 * @date 2020/07/30 16:13
 * @email wangyandong@inspur.com
 */
@Slf4j
//@Component("applicationEventMulticaster")s
public class CAFApplicationEventMulticaster extends SimpleApplicationEventMulticaster {

//    /*Executor 不能直接直接返回Executor，需要把exceutor注入到对应单例的bean中*/
//    @Override
//    protected Executor getTaskExecutor() {
//        Executor executor = super.getTaskExecutor();
//        if (null == executor) {
//            ThreadFactory threadFactory = new DefaultThreadFactory("event-factory");
//            super.setTaskExecutor(Executors.newFixedThreadPool(5, threadFactory));
//        }
//        return super.getTaskExecutor();
//    }

    @Override
    protected ErrorHandler getErrorHandler() {
        ErrorHandler handler = super.getErrorHandler();
        if (null == handler) {
            handler = new ErrorHandler() {
                @Override
                public void handleError(Throwable t) {
                    log.error("error in event process", t);
                }
            };
            super.setErrorHandler(handler);
        }
        return super.getErrorHandler();
    }

    @Override
    protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
        if(log.isDebugEnabled()) {
            if (event instanceof io.iec.edp.caf.commons.event.StartupCompletedEvent)
                log.debug("Now new listener start invoke " + listener.getClass().getName());
            if (event instanceof io.iec.edp.caf.boot.event.startup.StartupCompletedEvent)
                log.debug("Now old listener start invoke " + listener.getClass().getName());
        }
        super.invokeListener(listener, event);
    }
}
